/**
 * 
 */
package travibot.connection.cookies;

import java.io.IOException;
import java.net.CookieHandler;
import java.net.URI;
import java.util.Collections;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import travibot.connection.ConnectionFactory;


/**
 * @author tajzivit
 *
 */
public class TraviBotCookieHandler extends CookieHandler {

    private static final String SET_COOKIE = "Set-Cookie";
    private static final String COOKIE = "Cookie";

    /* (non-Javadoc)
     * @see java.net.CookieHandler#get(java.net.URI, java.util.Map)
     */
    @Override
    public Map<String, List<String>> get(URI arg0, Map<String, List<String>> arg1) throws IOException {

        Map<String, List<String>> result = new Hashtable<String, List<String>>();
        
        ICookieHolder cookieHolder = ConnectionFactory.getFactory().getCookieHolder();
        
        List<String> cookies = null;
        
        if(cookieHolder.getCookies().size() > 0){
            cookies = Collections.singletonList(cookieHolder.getCookies().get(0).toString());
            result.put(COOKIE, cookies);
        }
         
        return result;
    }

    /* (non-Javadoc)
     * @see java.net.CookieHandler#put(java.net.URI, java.util.Map)
     */
    @Override
    public void put(URI arg0, Map<String, List<String>> arg1) throws IOException {

        List<String> cookieList = arg1.get(SET_COOKIE);
        
        if(null == cookieList)
            return;
        
        ICookieHolder cookieHolder = ConnectionFactory.getFactory().getCookieHolder();
        
        cookieHolder.clear();
        
        Iterator<String> cookieIterator = cookieList.iterator();
        
        while(cookieIterator.hasNext()){
            
            cookieHolder.addCookie(new Cookie(cookieIterator.next()));
        }
    }

}
